﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using HtmlPictureHelper.Model;
using HtmlAgilityPack;
using System.Configuration;
using HtmlPictureHelper.Enums;
using System.IO;
namespace HtmlPictureHelper.Analyzer
{
    /// <summary>
    /// 图片分析器
    /// </summary>
    public class PictureAnalyzer :BaseAnalyzer,Interface.IPictureAnalyzer
    {
        
        /// <summary>
        /// 表达式字典集合
        /// </summary>
        public Dictionary<ExpressionDictionaryKeys, string> ExpressionDictionary { get; set; }

        public PictureAnalyzer(string enterLink):base(enterLink)
        {
            //重新对HtmlDocument赋值，因为获取到该网站的编码是错误的
            string htmlString = base.HttpGet(enterLink, Encoding.GetEncoding("gbk"));
            this.HtmlDocument.LoadHtml(htmlString);
            //加载表达式配置项目
            ExpressionDictionary = new Dictionary<ExpressionDictionaryKeys, string>()
            {
                //图片标题表达式
                { ExpressionDictionaryKeys.PictureCaption,App.Default.PictureCaptionExpression},
                //单个图片链接表达式
                { ExpressionDictionaryKeys.PictureSingleLinkOld, App.Default.PictureSingleLinkExpression},
                //图片数量表达式（多个以逗号分隔）
                { ExpressionDictionaryKeys.PictureCount,App.Default.PictureCountExpressions }
            };
            
        }
        /// <summary>
        /// 获取图片分析模型
        /// </summary>
        /// <returns></returns>
        public AnalyzedPictureModel GetAnalyzedPictureModel()
        {
            AnalyzedPictureModel model = new AnalyzedPictureModel()
            {
                PictureCaption = GetPictureCaption(),
            };
            int pictureCount = GetPictureCount()*2;
            string singlePictureLink = GetSinglePictureLink();
            if(string.IsNullOrEmpty(singlePictureLink) || pictureCount <= 0)
            {
                return null;
            }
            string fileExtensionName = Path.GetExtension(singlePictureLink);
            string linkDirectoryName =singlePictureLink.Substring(0, singlePictureLink.LastIndexOf('/'));
            IList<Uri> pictureDownloadLinks = new List<Uri>();
            string fullLinkName = "";
            for (int i=1;i<=pictureCount;i++)
            {
                fullLinkName = $"{linkDirectoryName}/{i.ToString("00")}{fileExtensionName}";
                pictureDownloadLinks.Add(new Uri(fullLinkName));
            }
            model.PictureLinks = pictureDownloadLinks;
            return model;
        }
        /// <summary>
        /// 获取图片标题
        /// </summary>
        /// <returns></returns>
        public string GetPictureCaption()
        {
            string caption = base.GetHtmlNodeInnerText(ExpressionDictionary[ExpressionDictionaryKeys.PictureCaption]);
            caption = caption.Replace("\r\n", "").Replace(" ", "");
            return caption;
        }
        /// <summary>
        /// 获取图片数量
        /// </summary>
        /// <returns></returns>
        public int GetPictureCount()
        {
            string[] splitedExpression = ExpressionDictionary[ExpressionDictionaryKeys.PictureCount]?.Split(new char[] { ',' });
            if(splitedExpression == null || splitedExpression.Length <=0)
            {
                return 0;
            }
            string countText = "";
            foreach (var item in splitedExpression)
            {
                countText = base.GetHtmlNodeInnerText(item);
                if(!string.IsNullOrEmpty(countText))
                {
                    break;
                }
            }
            if (string.IsNullOrEmpty(countText))
            {
                return 0;
            }
            int count = Convert.ToInt32(countText);
            return count;
        }
        /// <summary>
        /// 获取单个图片的下载链接
        /// </summary>
        /// <returns></returns>
        public string GetSinglePictureLink()
        {
            HtmlNode node = HtmlDocument.DocumentNode.SelectSingleNode(ExpressionDictionary[ExpressionDictionaryKeys.PictureSingleLinkOld]);
            return node?.Attributes["src"]?.Value ?? "";
        }
    }
}
